package com.hp.bon.sgw.dr;

import com.hp.ocs.diameter.message.Message;
import com.hp.ocs.diameter.node.NotARequestException;
import com.hp.ocs.diameter.node.Peer;
import com.hp.ocs.diameter.node.StaleConnectionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DrDCCAsynCallHandler
{
  private static final Logger logger = LoggerFactory.getLogger(DrDCCAsynCallHandler.class);
  Message request;
  Peer peer;
  DrproxyChannel drproxyChannel;

  public DrDCCAsynCallHandler(Message request, Peer peer, DrproxyChannel drproxyChannel)
  {
    this.drproxyChannel = drproxyChannel;
    this.request = request;
    this.peer = peer;
  }

  public void onCallResult(DrCallParam drCallParam)
  {
    if (this.peer == null) {
      return;
    }
    if (drCallParam.getRetCode() > 10000) {
      this.drproxyChannel.directReplyCCAWithServiceResultCode(
        this.request, this.peer, drCallParam.getRetCode(), null);
    }
    else
      this.drproxyChannel.directReplyCCA(this.request, this.peer, 
        drCallParam.getRetCode(), null);
  }

  public int getProtocolType()
  {
    return 1;
  }

  public int forwardReqeust(DrCallParam drCallParam)
  {
    Peer toPeer = this.drproxyChannel.getNodeConnect(drCallParam.getToPeerHostId());
    if (toPeer == null)
    {
      drCallParam.setWait4Resend(true);
      logger.warn("checkSend is true, but toNode is not connected. wait for resend.");
      return 0;
    }

    if ((drCallParam.getRequest() instanceof Message))
    {
      Message req = drCallParam.getRequest();
      try
      {
        this.drproxyChannel.sendRequest(req, toPeer, req);
      }
      catch (StaleConnectionException e)
      {
        e.printStackTrace();
      } catch (NotARequestException e) {
        e.printStackTrace();
      }
    }
    else {
      logger.warn("not expected Message type");
      return -1;
    }

    return 0;
  }

  public int resend2Slave(DrCallParam drCallParam)
  {
    Peer toPeer = this.drproxyChannel.getNodeConnect(drCallParam.getToPeerHostId());
    Message req = drCallParam.getRequest();
    if (toPeer != null)
    {
      drCallParam.setWait4Resend(false);
      this.drproxyChannel.diameterSendRequest(req, toPeer, req);
    }
    else
    {
      logger.warn("slave business NE is not connected, resend2Slave fail, wait for DrproxyMessageQueue recheck.");
    }
    return 0;
  }
}
